//
//  ViewController.m
//  Download
//
//  Created by Maurice on 2021/7/17.
//

#import "ViewController.h"
#import "Downloader.h"

@interface ViewController ()

@property(nonatomic, strong) Downloader *testDownloader;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self duplicatedDownload];
}


- (void)duplicatedDownload
{
    /*
     这里有两个一样的下载任务, 理论上他们都会成功，你需要做的是，在不改动以下两个下载任务的successHandler和failureHadler的情况下，完成以下功能
     1. 使第一个任务会被马上取消
     2. 保证task1和task2的回调顺序
     3. 思考重复下载时的Downloader该如何优化
     */
    
    _testDownloader = [[Downloader alloc] init];
    
    NSURL *url = [NSURL URLWithString:@"https://api.github.com/users"];
    
   [_testDownloader downloadWithURL:url successHandler:^(NSURL * _Nonnull URL, NSURLResponse * _Nullable response) {
       @throw [NSException exceptionWithName:@"Task1 Error" reason:@"Task1 could not succeed" userInfo:nil];
    } failureHadler:^(NSError * error) {
        if (error.code != NSURLErrorCancelled) {
            @throw [NSException exceptionWithName:@"Task1 Error" reason:@"Task1 must be cancelled" userInfo:nil];
        }
    }];
    
    [_testDownloader downloadWithURL:url successHandler:^(NSURL * _Nonnull URL, NSURLResponse * _Nullable response) {
        NSLog(@"duplicatedDownload方法完成");
    } failureHadler:^(NSError * error) {
        @throw [NSException exceptionWithName:@"Task2 Error" reason:@"Task1 must be cancel" userInfo:nil];
    }];
}

@end
